import Vue from 'vue'
// 按需引入uView核心JS（非组件部分）
import { $u } from '@/uni_modules/uview-ui'
Vue.prototype.$u = $u

// 然后再引入App
import App from './App'

// vuex数据管理中心
import store from '@/store'
Vue.prototype.$store = store;

// 公共组件
import publicModule from "@/components/public-module.vue";
Vue.component("public-module", publicModule);

// request
import '@/config/request.js';

// 地址白名单
const whiteList = [
  '/pages/index/index', '/pages/mine/index',
  '/pages/papers/components/detail', '/pages/post/index',
   '/pages/papers/index','/pages/papers/category',
   '/pages/papers/components/detail',
   '/pages/articles/index','/pages/original/index',
   '/pages/calculation/index','/pages/idiom/index',
   '/pages/idiom/study','/pages/idiom/dictation',
   '/pages/studygroup/detail','/pages/calculation/data-search/index',
   '/pages/calculation/estimation/index','/pages/calculation/pk-battle/create-room',
   '/pages/articles/components/detail','/pages/articles/components/add',
   '/pages/idiom/index','/pages/focus/index',
   '/pages/calculation/estimation/leaderboard'
]

// 检查地址白名单
const checkWhite = (url) => {
  const path = url.split('?')[0]
  return whiteList.indexOf(path) !== -1
}

// 检查用户信息是否完整
const checkUserInfo = () => {
  const user = store.state.user
  return user && user.major && user.preparationCity && user.fullTime
}

// 页面跳转验证拦截器,是否需要登录判断
uni.addInterceptor("navigateTo", {
  invoke(to) {
    // 如果是跳转到个人信息页面，允许通过
    if (to.url.includes('/pages/mine/components/add')) {
      return true
    }
    
    if (store.state.token) {
      // 已登录用户检查信息完整性
      if (!checkUserInfo()) {
        uni.showModal({
          title: '提示',
          content: '请先完善个人信息',
          showCancel: false,
          success: () => {
            uni.navigateTo({
              url: '/pages/mine/components/add?required=true'
            })
          }
        })
        return false
      }
      return true
    } else {
      if (checkWhite(to.url)) {
        return true
      }
      // 静默登录机制，直接跳转到首页
      uni.reLaunch({
        url: '/pages/index/index'
      });
      return false
    }
  }
})

// 拦截 switchTab 跳转
uni.addInterceptor("switchTab", {
  invoke(to) {
    if (store.state.token) {
      // 已登录用户检查信息完整性
      if (!checkUserInfo()) {
        uni.showModal({
          title: '提示',
          content: '请先完善个人信息',
          showCancel: false,
          success: () => {
            uni.navigateTo({
              url: '/pages/mine/components/add?required=true'
            })
          }
        })
        return false
      }
      return true
    } else {
      if (checkWhite(to.url)) {
        return true
      }
      // 静默登录机制，直接跳转到首页
      uni.reLaunch({
        url: '/pages/index/index'
      });
      return false
    }
  }
})

Vue.config.productionTip = false
App.mpType = 'app'

const app = new Vue({
  ...App
})

app.$mount()